//
import storage from "@/plugins/storage";
import globalConfig from "@/config";

import request from "@/plugins/request";

import { getLocalUrlParam, isWechat } from "@/plugins/utils";

/* import { apiLogin, apiCreateAccount, apiAuth, apiLogout } from "@/api/ucenter/auth";

import { apiUploadAvatar, apiGetUserInfo } from "@/api/ucenter";
 */
const token = storage.get("token") || "";

const user = storage.get("user") || {};

const userExtend = storage.get("userExtend") || {};

const avatar = user.avatar || "";

const nickname = user.nickname || user.username || "";

const state = {
  token,
  nickname,
  avatar,
  user,
  userExtend,
  isWxPrivacy: false, //是否同意了微信隐私协议
};

const mutations = {
  setToken: (state, token) => {
    storage.set("token", token);
    state.token = token;
  },

  getToken: (state) => {
    return state.token;
  },
  //删除token
  removeToken: (state) => {
    storage.remove("token");
    state.token = "";
  },

  setNickname: (state, nickname) => {
    state.nickname = nickname;
  },

  setAvatar: (state, avatar) => {
    state.avatar = avatar;
  },

  setUser: (state, user) => {
    storage.set("user", user);
    state.nickname = user.nickname || user.username;
    state.avatar = user.avatar || "";
    state.user = user || {};
  },

  setUserExtend: (state, userExtend) => {
    state.userExtend = {
      ...state.userExtend,
      ...userExtend,
    };
    storage.set("userExtend", userExtend);
  },

  // 删除user
  removeUser: (state) => {
    state.nickname = "";
    state.avatar = "";
    state.user = {};
    state.userExtend = {};
    storage.remove("user");
    storage.remove("userExtend");
  },
};

const actions = {
  getToken({ commit, state }) {
    return new Promise((resolve) => {
      if (state.token) {
        resolve(state.token);
      } else {
        const token = storage.get("token") || "";
        commit("setToken", token);
        resolve(token);
      }
    });
  },

  // 创建账户
  createAccount({ commit }, data) {
    return new Promise((resolve, reject) => {
      apiCreateAccount(data).then((res) => {
        if (res.status === 200) {
          commit("setToken", res.token);
          commit("setUser", res.user);
          resolve(res);
        } else {
          resolve(res);
        }
      });
    });
  },

  // 上传头像
  uploadAvatar({ commit, state }, data) {
    return new Promise((resolve, reject) => {
      apiUploadAvatar(data)
        .then((res) => {
          if (res.status === 200) {
            commit("setAvatar", res.avatar);
            commit("setUser", res.user);

            resolve(res);
          } else {
            resolve(res);
          }
        })
        .catch((err) => {
          resolve(err);
        });
    });
  },

  // user login
  login({ commit }, data) {
    return new Promise((resolve, reject) => {
      apiLogin(data)
        .then((res) => {
          if (res.status === 200) {
            commit("setToken", res.token);
            commit("setUser", res.user);
            resolve(res);
          } else {
            reject(res);
          }
        })
        .catch((err) => {
          reject(err);
        });
    });
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      apiLogout({
        oauth: "wechat",
      })
        .then(() => {
          dispatch("clear");
          resolve();
        })
        .catch((err) => {
          reject(err);
        });
    });
  },

  getUserInfo({ commit, state }, options = { loading: true }) {
    return new Promise((resolve, reject) => {
      apiGetUserInfo(
        {
          token: state.token,
          oauth: "wechat",
        },
        options,
      )
        .then((res) => {
          if (res.status === 200) {
            commit("setUser", res.user);
            resolve(res);
          } else {
            reject(res);
          }
        })
        .catch((err) => {
          reject(err);
        });
    });
  },

  auth(
    { commit, state, dispatch },
    options = { loading: true, data: {}, resData: false, redirect: "" },
  ) {
    return new Promise((resolve, reject) => {
      if (state.token || storage.get("token")) {
        return resolve(state.token);
      } else {
        // #ifdef H5

        /* 微信公众号授权验证 */

        if (isWechat()) {
          const code = getLocalUrlParam("code");
          if (code) {
            if (state.token || storage.get("token")) {
              return resolve(state.token);
            }
            // 如果有code，则获取用户信息
            dispatch("wechatOfficialAccountAuth", options)
              .then((res) => {
                resolve(res);
              })
              .catch((err) => {
                reject(err);
              });
          } else {
            // 则跳转到微信授权页面
            let redirect = encodeURIComponent(window.location.href);

            if (options.redirect) {
              redirect = encodeURIComponent(options.redirect);
            }
            if (!storage.get("redirect")) {
              console.log("redirect", redirect);
              storage.set("redirect", redirect);
            }

            const redirect_uri = encodeURIComponent(`${globalConfig.domain}/pages/home/index`);
            let url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${globalConfig.wechat.officialAccount.appid}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`;

            window.location.href = url;
            return reject();
          }
        } else {
          reject({
            status: 500,
            msg: "请在微信中打开！",
          });
        }

        // #endif

        // #ifdef MP-WEIXIN

        /* 微信小程序授权验证 */
        dispatch("mpWechatAuth", options)
          .then((res) => {
            resolve(res);
          })
          .catch((err) => {
            reject(err);
          });

        // #endif
      }
    });
  },

  //微信小程序授权验证
  /**
   * @description:
   * @param {*} commit // 提交mutations
   * @param {*} dispatch // 提交actions
   * @param {*} options // 参数 { loading: true, resData: false, code: "" } loading:是否显示加载中 resData:是否返回数据 code:微信code
   * @return {Promise}
   */
  mpWechatAuth(
    { commit, dispatch },
    options = { loading: true, resData: false, code: "", redirect: "" },
  ) {
    return new Promise(async (resolve, reject) => {
      /**
       * @options 参数说明
       * @param {Boolean} loading 是否显示加载中
       * @param {Boolean} resData 是否返回数据
       * @param {String} code 微信code
       * @param {String} redirect 跳转地址
       */

      let { loading, resData, code, redirect } = options;

      // 如果没有传入code，则获取code
      if (!code) {
        // uni.login() 返回值
        const [err, res] = await uni.login({
          provider: "weixin",
        });

        if (err) {
          uni.showToast({
            title: "微信小程序授权失败：" + err.errMsg,
            icon: "none",
          });
          return reject(err);
        }

        code = res.code;
      }

      if (!code) {
        const msg = "微信小程序授权失败，请重试！";
        uni.showToast({
          title: msg,
          icon: "none",
        });
        return reject({
          status: 500,
          msg: msg,
        });
      }

      // 将code传给后端，获取openid
      apiAuth(
        {
          code,
          oauth: "wechat", //授权协议 微信小程序 wechat 微信公众号 wechatofficial
        },
        {
          loading,
        },
      )
        .then((res) => {
          commit("setToken", res.token);
          commit("setUser", res.user);
          console.log("redirect", redirect);
          if (resData) {
            //是否返回数据
            console.log("是否返回数据", resData);
            return resolve(res);
          } else {
            uni.showToast({
              title: "登录成功！",
              icon: "none",
            });

            dispatch("getUserInfo");

            uni.navigateTo({
              url: redirect || "/pages/home/index",
              success: () => {},
            });
          }
        })
        .catch((err) => {
          return reject(err);
        });
    });
  },

  wechatOfficialAccountAuth({ commit, dispatch }, options = { loading: true }) {
    return new Promise(async (resolve, reject) => {
      let { loading } = options;

      // 获取code
      const code = getLocalUrlParam("code");

      if (!code) {
        const msg = "微信公众号授权失败，请重试！";
        uni.showToast({
          title: msg,
          icon: "none",
        });
        return reject({
          status: 500,
          msg: msg,
        });
      }

      // 将code传给后端，获取openid
      apiAuth(
        {
          code,
          oauth: "wechatofficial", //授权协议 微信小程序 wechat 微信公众号 wechatofficial
        },
        {
          loading,
        },
      )
        .then((res) => {
          commit("setToken", res.token);
          commit("setUser", res.user);

          uni.showToast({
            title: "登录成功！",
            icon: "none",
          });

          dispatch("getUserInfo");

          let redirect = storage.get("redirect");
          if (redirect) {
            storage.remove("redirect");
            window.location.href = decodeURIComponent(redirect);
          } else {
            redirect = options.redirect || "/pages/home/index";

            uni.navigateTo({
              url: redirect,
              success: () => {},
              fail: () => {
                uni.switchTab({
                  url: redirect,
                  success: () => {},
                  fail: () => {
                    uni.reLaunch({
                      url: redirect,
                      success: () => {},
                    });
                  },
                });
              },
            });
          }

          return resolve(res);
        })
        .catch((err) => {
          return reject(err);
        });
    });
  },

  updateUserExtend({ commit, state }, data) {
    state.userExtend = {
      ...state.userExtend,
      ...data,
    };
    return new Promise((resolve, reject) => {
      request({
        url: "/api/user/updateExtend",
        method: "POST",
        data: {
          token: state.token,
          extend: state.userExtend,
        },
      })
        .then((res) => {
          commit("setUser", res.user);
          resolve(res);
        })
        .catch((err) => {
          resolve(err);
        });
    });
  },

  // remove token
  clear({ commit }) {
    return new Promise((resolve) => {
      commit("removeToken");
      commit("removeUser");

      commit("setNickname", "");
      commit("setAvatar", "");

      resolve();
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
